/*
 * FtpFacade.java
 *
 * Copyright 2007, 2008 Tiberiumlabs
 *
 * This file is part of Tiberiumlabs Lailaps.
 *
 * Tiberiumlabs Lailaps is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Tiberiumlabs Lailaps is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.tiberiumlabs.lailaps.threads.single;

import java.io.IOException;
import java.io.InputStream;
import java.util.ResourceBundle;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.tiberiumlabs.lailaps.Mediator;
import org.tiberiumlabs.lailaps.gui.authorize.AuthorizationBean;
import org.tiberiumlabs.lailaps.gui.authorize.AuthorizationCanceled;
import org.tiberiumlabs.lailaps.settings.NetworkSettings;
import org.tiberiumlabs.lailaps.settings.Settings;
import org.tiberiumlabs.lailaps.toolkit.Constants;

/**
 * @author <a href="mailto:paranoid.tiberiumlabs@gmail.com">Paranoid</a>
 */
public class FtpFacade implements MethodFacade {

    private static final String LATIN_1 = "ISO-8859-1";
    
    private static final NetworkSettings NETWORK_SETTINGS = Settings.getNetworkSettings();

    private ResourceBundle bundle = null;
    
    private String url = null;
    
    private long offset = 0;
    
    private String fileName = null;
    
    private FTPClient get = null;
    
    private FTPFile file = null;
    
    private InputStream inputStream = null;

    @Override
    public void setBundle(ResourceBundle bundle) {
        this.bundle = bundle;
    }

    @Override
    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    public void setOffset(long offset) {
        this.offset = offset;
    }

    @Override
    public void execute() throws IOException {

        // TODO more messages to log, like in HttpFacade
        // preparing host name. TODO think if we need check correctness of FTP url...
        int index = url.indexOf('/', 6);
        if (index == -1) {
            throw new IllegalArgumentException("illegal FTP url: " + url);
        }
        String host = url.substring(6, index);

        // preparing working directory:
        int lastIndex = url.lastIndexOf('/');
        if (lastIndex == -1) {
            throw new IllegalArgumentException("illegal FTP url: " + url);
        }
        String workingDir = url.substring(index, lastIndex);

        // preparing file name:
        fileName = url.substring(lastIndex + 1);
        // </editor-fold>
        // <editor-fold defaultstate="collapsed" desc=" setuping FtpClient ">
        get = new FTPClient();

        get.setBufferSize(NETWORK_SETTINGS.getDownloadBufferSize());
        get.setDataTimeout(NETWORK_SETTINGS.getFtpDataTimeout());

        get.connect(host);

        //let's try loging anonymously
        get.login("anonymous", "anonymous");

        //failed? If so ask user for login/password pair
        try {
            while (!FTPReply.isPositiveCompletion(get.getReplyCode())) {
                AuthorizationBean credentials = Mediator.getMediator().getGuiBuilder().getAuthorizationDialog().performLogin();
                get.login(credentials.getLogin(), credentials.getPassword());
            }
        } catch (AuthorizationCanceled ex) {
            //TODO stop download somehow normally?
            throw new RuntimeException("Download failed due to authorization issue");
        }

        get.setTcpNoDelay(NETWORK_SETTINGS.isFtpTcpNoDelay());

        if (NETWORK_SETTINGS.getFtpModeType() == Constants.FTP_MODE_PASSIVE) {
            get.enterLocalPassiveMode();
        }

        switch (NETWORK_SETTINGS.getFtpTransferType()) {
            case Constants.FTP_TRANSFER_BINARY:
                get.setFileType(FTP.BINARY_FILE_TYPE);
                break;
            case Constants.FTP_TRANSFER_BINARY_IMAGE:
                get.setFileType(FTP.IMAGE_FILE_TYPE);
                break;
            case Constants.FTP_TRANSFER_ASCII:
                get.setFileType(FTP.ASCII_FILE_TYPE);
                break;
            case Constants.FTP_TRANSFER_EBCDIC:
                get.setFileType(FTP.EBCDIC_FILE_TYPE);
                break;
        }

        for (String encoding : NETWORK_SETTINGS.getCharsetList()) {

            // setting next encoding before doing any actions
            get.setControlEncoding(encoding);

            // IT seems that FTP can switch directories by sending only ISO-8859-1 (Latin-1)
            // commands so we'll try it first.
            if (get.changeWorkingDirectory(workingDir) || get.changeWorkingDirectory(new String(workingDir.getBytes(encoding), LATIN_1))) {

                /*
                 * FTPClient will returt array of files, they seems to be equal
                 * but with dirrefent names. if it will return empty array - we
                 * will try next encoding.
                 */
                FTPFile[] ftpFiles = get.listFiles(fileName);
                if (ftpFiles.length > 0) {
                    file = ftpFiles[0];
                    inputStream = get.retrieveFileStream(file.getName());
                }

                /*
                 * if input stream is not empty - we got it, nothing more to do
                 * here. if empty - just try next encoding.
                 */
                if (inputStream != null) {
                    break;
                }
            }
        }

        /*
         * if we tryed all encodings and input stream is still empty...
         */
        if (inputStream == null) {
            // TODO i18n
            throw new IllegalStateException("FTP file not found!");
        }

        if (offset > 0) {
            get.setRestartOffset(offset);
        }
    }

    @Override
    public long getLength() {
        return file.getSize();
    }

    @Override
    public long getDate() {
        if (file != null) {
            return file.getTimestamp().getTimeInMillis();
        }
        return 0;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        //return get.retrieveFileStream(fileName);
        return inputStream;
    }

    @Override
    public void close() throws IOException {
        // TODO check why logout hangs
        //get.logout();
        get.disconnect();
    }

    @Override
    public void abort() throws IOException {
        /*
         * TODO works good only stupid disconnect, but
         * according to javadoc we need to use abort in this case.
         */
        //get.abort();
        //get.logout();
        get.disconnect();
    }
}
